<?php

namespace app\index\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Balance;
use app\common\controller\CardCustom;
use app\common\controller\CardPut;
use app\common\controller\CardPuttest;
use app\common\controller\CreateNotify;
use app\common\controller\Fztest;
use app\common\controller\UserBonusFee;
use app\common\model\CardConsume;
use app\common\model\CardCzLog;
use app\common\model\CardFans;
use app\common\model\CardFollowcardlog;
use app\common\model\CardFreecard;
use app\common\model\CardFreecardlog;
use app\common\model\CardGift;
use app\common\model\CardGivecardLog;
use app\common\model\CardLeaduser;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardShareLog;
use app\common\model\CardShareRule;
use app\common\model\CardShareUser;
use app\common\model\CardUserBonus;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\CardPutRule;
use app\common\model\CardUserGetGift;
use app\common\model\CardUserUpdate;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\WxOpen;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\merchant\controller\Qrcodes;
use app\common\model\System;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Wxcard extends Controller
{

    //审核卡券
    public function cardpass($datas)
    {
        $data['notpass'] = $datas['notpass'];
        $data['notpassinfo'] = !empty($datas['notpassinfo'])?$datas['notpassinfo']:"";
        $CardMember = new CardMember();
        if (!empty($datas['cardid'])) {
            $res = $CardMember->save($data, ['card_id' => $datas['cardid']]);
            if (!$res) {
                $CardGeneral = new CardGeneral();
                $CardGeneral->save($data, ['card_id' => $datas['cardid']]);
            }
        }
    }

    //审核门店
    public function storepass($datas)
    {
        $map['top_mid'] = $datas['sid'];
        $map['poi_id'] = $datas['poi_id'];
        if ($datas['result'] == 'succ') {
            $data['pass_statu'] = 1;
        } else {
            $data['pass_statu'] = 3;
        }
        $data['pass_res'] = $datas['result'];
        $data['pass_msg'] = $datas['pass_msg'];
        $Merchant = new Merchant();
        $Merchant->save($data, $map);
    }

    //领取
    public function usergetcard($datas)
    {
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos", "wxauth", "event/getcard", "1:", $datas);

        $this->recdata($datas);
        $map['card_id'] = $datas['CardId'];
        $data = $this->getdata($datas);
        //实例化模型
        $CardMember = new CardMember();
        $CardUserget = new CardUserGet();
        //获取data数据
//        $ActionLogs->writelog("payos", "wxauth", "event/getcard", "2:", $data);
        $data['card_type'] = $this->gettype($map);          //卡券类别
//        $ActionLogs->writelog("payos", "wxauth", "event/getcard", "3:", $data);
        //不是该平台创建的卡则结束该方法
        if (empty($data['card_type'])) {
            exit();
        }
        //礼品卡领取则转到礼品卡记录
        if ($data['card_type'] == 'GENERAL_CARD'){
            $this->recgetcardgift($data);
            exit();
        }
        $CreateNotify = new CreateNotify();
        //领取为会员卡则获取激活状态
        if ($data['card_type'] == 'MEMBER_CARD') {
            $cardinfos = $this->getcardmeinfo($map['card_id']);
            $activate = $CardMember->where($map)->value('activate');                 //获取本会员卡的激活状态
            $data['fire'] = $activate == 2 ? 1 : 0;                                         //判断该张会员卡是否自动激活 如果是则将领取状态改为激活   1/0
            $data['mid'] = $cardinfos['mid'];
            $data['c_id'] = $cardinfos['id'];
            $data['top_mid'] = $cardinfos['top_mid'];
            $mapis['card_id'] = $data['card_id'];
            $mapis['code'] =  $data['code'];
            $usercodeinfo = $CardUserget->where($mapis)->field('openid,is_sync,fire')->find();          //判断是否存在
//            $ActionLogs->writelog("payos", "wxauth", "event/getcard", "cz:", $CardUserget->getLastSql());
            if ($usercodeinfo) {

                $map['code'] = $data['code'];

                //END
                if (isset($data['outerstr'])){
                    $dataz['outerstr'] = $data['outerstr'];
                }
                //END   unionid
                if (isset($data['sourec'])){
                    $dataz['sourec'] = $data['sourec'];
                }
                //END
                if (isset($data['unionid'])){
                    $dataz['unionid'] = $data['unionid'];
                }
                //是否是同步卡号
                if ($usercodeinfo['is_sync']=="N"){
                    $dataz = $data;
                    $dataz['is_sync']="Y";
                }
                $dataz['fire'] = $usercodeinfo['fire'] == 1?1:$data['fire'];
                $dataz['openid'] = $data['openid'];
                $dataz['have'] = 1;
                if ($dataz['fire'] == 1){
                    $dataz['fire_time'] = time();
                }
                //END
                $CardUserget->allowField(true)->where($mapis)->update($dataz);                    //如果是找回则更新数据   isbackcard  1/0  找回和领取
//                $ActionLogs->writelog("payos", "wxauth", "event/getcard", "zh:", $CardUserget->getLastSql());
            }else{
//                if ($data['have'] == 1) {                     //判断是否为找回操作
//                    $map['code'] = $data['code'];
//                    $dataz['have'] = 1;
//                    $CardUserget->where($mapis)->update($dataz);                    //如果是找回则更新数据   isbackcard  1/0  找回和领取
//                }
//                if ($data['have'] == 0 || !$usercodeinfo) {
//                    $code = $datas['UserCardCode'];
                    if ($data['fire'] == 1){
                        $data['fire_time'] = time();
                    }
                    $data['have'] = 1;
                    $CardUserget->allowField(true)->validate(['code'  => 'require|unique:CardUserGet'])->save($data);            //新增则存入数据
                    //分享奖励
                    $share['card_id'] = $data['card_id'];
                    $share['outerstr'] = $data['outerstr'];
                    $share['get_code'] = $data['code'];
                    $share['get_openid'] = $data['openid'];
                    $share['mid'] = $data['mid'];
                    $share['top_mid'] = $data['top_mid'];
                    $share['type'] = 'getcard';
                    $share = $this->shareget($share);
                    //领卡推送
                    $this->senduserget($CardUserget->id);
//                }
            }
            //写入领取用户信息处理
            $this->recgetuserinfo($mapis);
            //更新第三自定义类目
//            $this->update_cardus_cardsnum($data);
            //更新会员归属门店
            $this->rec_gsmid($mapis);
            //推送通知到第三方
            $CreateNotify->card_rec_notify($datas);

        } else {
//            $ActionLogs->writelog("payos", "wxauth", "event/getcard", "4:", $data);
            //卡券数据存入表
            $cardinfo = $this->getaddcardgel($data);
            if ($cardinfo['time_type'] == 'DATE_TYPE_FIX_TIME_RANGE'){
                $data['start_time'] = $cardinfo['begin_timestamp'];
                $data['end_time'] = $cardinfo['end_timestamp'];
            }
            if ($cardinfo['time_type'] == 'DATE_TYPE_FIX_TERM'){
                $data['start_time'] = time();
                $data['end_time'] = $cardinfo['fixed_term']*86400 + time();
            }
            if ($cardinfo['time_type'] == 'DATE_TYPE_PERMANENT'){
                $data['start_time'] = time();
                $data['end_time'] = strtotime("+15 year");
            }
            $data['type_time'] = $cardinfo['time_type'];
            $data['top_mid'] = $cardinfo['top_mid'];
            $data['mid'] = $cardinfo['mid'];
            $data['have'] = 1;
            $data['fire'] = 1;
            $data['create_time'] = time();
//            $ActionLogs->writelog("payos", "wxauth", "event/getcard", "5:", $data);
            $resinc = $CardUserget->allowField(true)->save($data);
//            $ActionLogs->writelog("payos", "wxauth", "event/getcard", "6:", $resinc);
            $this->getgivecards($data);         //充值
            $this->getshopcards($data);         //购买
//            $this->freeputcards($data);         //免费
            //改变转赠卡号状态
            if ($data['isgivecard'] ==1){
                $mas['code'] = $data['oldcodes'];
                $CardUserget->where($mas)->update(['have'=>2]);

            }
            //推送通知到第三方
            $CreateNotify->quan_rec_notify($datas);
            //更新第三自定义类目
//            $this->update_cardus_cardsnum($data);

        }
    }

    //获取卡券创建数据
    public function getaddcardgel($param){
        $CardGel = new CardGeneral();
        $cardinfo = $CardGel->where(['card_id'=>$param['card_id']])->field('top_mid,mid,time_type,fixed_term,begin_timestamp,end_timestamp')->find();
        if (!$cardinfo){
            $cardinfo = ['top_mid'=>0,'mid'=>0];
        }
        return $cardinfo;

    }

    //写入礼品卡领取记录
    public function recgetcardgift($param){
        try {
            $CardUserGetCift = new CardUserGetGift();
            $isget = $CardUserGetCift->where(['code'=>$param['code'],'card_id'=>$param['card_id']])->value('id');
            if ($isget){
                $data['have'] = 1;
                $CardUserGetCift->allowField(true)->save($data,['code'=>$param['code'],'card_id'=>$param['card_id']]);
            }else{
                $data = $param;
                $cardinfo = $this->getaddcardgift($param);
                if ($cardinfo['type_time'] == 'DATE_TYPE_FIX_TIME_RANGE'){
                    $data['start_time'] = $cardinfo['begin_time'];
                    $data['end_time'] = $cardinfo['end_time'];
                }
                if ($cardinfo['type_time'] == 'DATE_TYPE_FIX_TERM'){
                    $data['start_time'] = time();
                    $data['end_time'] = $cardinfo['fixed_term']*86400 + time();
                }
                if ($cardinfo['type_time'] == 'DATE_TYPE_PERMANENT'){
                    $data['start_time'] = time();
                    $data['end_time'] = strtotime("+100 year");
                }
                $data['type_time'] = $cardinfo['type_time'];
                $data['top_mid'] = $cardinfo['top_mid'];
                $data['mid'] = $cardinfo['mid'];
                $data['have'] = 1;
                $CardUserGetCift->allowField(true)->validate(['code'  => 'require|unique:CardUserGet'])->save($data);
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
    }

    //获取礼品卡创建数据
    public function getaddcardgift($param){
        $CardGift = new CardGift();
        $cardinfo = $CardGift->where(['card_id'=>$param['card_id']])->field('top_mid,mid,type_time,fixed_term,begin_time,end_time')->find();
        if (!$cardinfo){
            $cardinfo = ['top_mid'=>0,'mid'=>0];
        }
        return $cardinfo;
    }

    //将发送数据写入文件
    public function recdata($data){
        try {

//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","getcard","e:",$data);
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => $e->getMessage());

        }
    }

    //卡号记录是否存在
    public function iscardcode($arr){

        try {
            $CardUserget = new CardUserGet();
            $map['card_id'] = $arr['card_id'];
            $map['code'] = $arr['code'];

            $user = $CardUserget->where($map)->value('openid');

            if ($user){
                $res = 1;
            }else{
                $res = 0;
            }

        } catch (\Exception $e) {
            $res = 0;
        }

        return $res;
    }

    //领卡推送
    private function senduserget($id){
        try {
            $url = 'http://v.wunengkeji.com/index.php/index/index/send/type/carduserlist/getid/'.$id;
            $res = $this->http_get($url);
        } catch (\Exception $e) {
            $res = $e->getMessage();

        }
    }

    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


    //激活送券
    public function firegivecards($arr)
    {

        try {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['card_id' => $arr['card_id'], 'code' => $arr['code']])->field('card_id,code,openid,nickname,top_mid,mid,fire')->find();
            if ($user['fire'] == 1 || $user['fire'] == "1"){
                $user['give_type'] = 'fire_card';
                $CardPut = new CardPut();
                $data2 = $CardPut->firecards($user);
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
    }

    //免费送券
    public function freeputcards($arr)
    {

        try {
            if (strpos($arr['outerstr'], 'PutId_')) {
                $outerstr = explode('_', $arr['outerstr']);
                $givelogid = end($outerstr);
                if ($givelogid) {
                    $CardFreecard = new CardFreecard();
                    $res = $CardFreecard->where(['id' => $givelogid])->setInc('get_num', 1);
                    $CardFreecardlog = new CardFreecardlog();
                    $map['openid'] = $arr['openid'];
                    $map['fid'] = $givelogid;
                    $isuser = $CardFreecardlog->where($map)->find();
                    if (!$isuser) {
                        $data['mid'] = $arr['mid'];
                        $data['openid'] = $arr['openid'];
                        $data['user_code'] = $arr['code'];
                        $data['fid'] = $givelogid;
                        $data['gettime'] = time();
                        $res = $CardFreecardlog->allowField(true)->save($data);
//                    $data['mid'] = $arr['mid'];
                    }
                }
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }

    }

    //卡券充值领取
    public function getgivecards($arr)
    {

        try {
            if (strpos($arr['outerstr'], 'RecId_')) {
                $outerstr = explode('_', $arr['outerstr']);
                $givelogid = end($outerstr);
                if ($givelogid) {
                    $CardGivecardLog = new CardGivecardLog();
                    $CardCzLog = new CardCzLog();
                    $give_rec_id = $CardGivecardLog->where(['id' => $givelogid, 'zs_card_id' => $arr['card_id']])->value('give_rec_id');
                    $CardCzLog->save(['zs_card_statu'=>1],['id'=>$give_rec_id]);
                    $res = $CardGivecardLog->where(['id' => $givelogid, 'zs_card_id' => $arr['card_id']])->setInc('get_sume', 1);
                }
            }
            $this->logtest($arr);
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => '系统错误'));
        }
    }

    private function logtest($param){
        try {
            if (strpos($param['outerstr'], 'RecId_')) {
                $outerstr = explode('_', $param['outerstr']);
                $givelogid = end($outerstr);
                if ($givelogid) {
                    $CardUserGet = new CardUserGet();
                    $getsum = $CardUserGet->where(['outerstr'=>$param['outerstr']])->count('id');
                    $CardGivecardLog = new CardGivecardLog();
                    $CardGivecardLog->save(['get_sume' => $getsum], ['id' => $givelogid, 'zs_card_id' => $param['card_id']]);
                }
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }

    }

    //卡券商城领取
    public function getshopcards($arr)
    {
        try {
            if (strpos($arr['outerstr'], 'hopExch_')) {
                $outerstr = explode('_', $arr['outerstr']);
                $orderid = end($outerstr);
                if ($orderid) {
                    $CardOrder = new CardOrder();
                    $res = $CardOrder->save(['statu' => 2, 'get_code' => $arr['code']], ['id' => $orderid]);
                }
            }
        } catch (\Exception $e) {
            $data2 = json_encode(array('code' => '9099', 'message' => '系统错误'));
        }
    }

    //领取字段处理
    public function getdata($datas)
    {
        //领取openid
        if (isset($datas['FromUserName'])) {
            $data['openid'] = $datas['FromUserName'];
        }else{
            $data['openid'] = "";
        }
        //领取时间
        if (isset($datas['CreateTime'])) {
            $data['create_time'] = $datas['CreateTime'];
        }else{
            $data['create_time'] = time();
        }
        //卡券id
        if (isset($datas['CardId'])) {
            $data['card_id'] = $datas['CardId'];
        }else{
            $data['card_id'] = "";
        }
        //卡号
        if (isset($datas['UserCardCode'])) {
            $data['code'] = $datas['UserCardCode'];
        }else{
            $data['code'] = "";
        }
        //是否转增
        if (isset($datas['IsGiveByFriend'])) {
            $data['isgivecard'] = $datas['IsGiveByFriend'];
        }else{
            $data['isgivecard'] = "";
        }
        //领取场景
        if (isset($datas['OuterStr'])) {
            $data['outerstr'] = $datas['OuterStr'];
        }else{
            $data['outerstr'] = "";
        }
        //是否找回
        if (isset($datas['IsRestoreMemberCard'])) {
            $data['have'] = $datas['IsRestoreMemberCard'];
        }else{
            $data['have'] = "1";
        }
        if (isset($datas['SourceScene'])) {
            $data['sourec'] = $datas['SourceScene'];
        }else{
            $data['sourec'] = "";
        }
        //unionid
        if (isset($datas['UnionId'])) {
            $data['unionid'] = $datas['UnionId'];
        }else{
            $data['unionid'] = "";
        }
        //转赠前卡号
        if (isset($datas['OldUserCardCode'])) {
            $data['oldcodes'] = $datas['OldUserCardCode'];
        }else{
            $data['oldcodes'] = "";
        }
        //转赠前openid
        if (isset($datas['FriendUserName'])) {
            $data['oldopenid'] = $datas['FriendUserName'];
        }else{
            $data['oldopenid'] = "";
        }
        return $data;
    }

    //获取会员卡mid top_mid id card_type等
    public function getcardmeinfo($card_id){
        $CardMember = new CardMember();
        $card = $CardMember->where(['card_id' => $card_id])->field('mid,top_mid,id,card_type')->find();
        return $card;
    }

    //商户ID
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //top_mid
    public function gettopmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('top_mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('top_mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //类别
    public function gettype($map)
    {
        $CardMember = new CardMember();
        $type = $CardMember->where($map)->value('card_type');
        if (empty($type)) {
            $CardGeneral = new CardGeneral();
            $type = $CardGeneral->where($map)->value('card_type');
            if (empty($type)){
                $CardGift = new CardGift();
                $type = $CardGift->where($map)->value('card_type');
                $CardGift->where($map)->setDec('stocks');    //库存减一
                $CardGift->where($map)->setInc('getsume');    //领取加1
            }else{
                $CardGeneral->where($map)->setDec('stocks');    //库存减一
                $CardGeneral->where($map)->setInc('getsume');    //领取加1
            }
            return $type;
        } else {
            $CardMember->where($map)->setDec('stocks');    //库存减一
            $CardMember->where($map)->setInc('getsume');    //领取加1
            return $type;
        }
    }

    //分享领取
    /*
     * 参数card_id  outerstr  openid code mid top_mid
     */
    public function shareget($arr)
    {

        //是否有规则
        if (strpos($arr['outerstr'], '_')) {
            $CardShareRule = new CardShareRule();
            //有无规则
            $only = $CardShareRule->where(['card_id' => $arr['card_id'], 'statu' => 0, 'rule_type' => 'SHARE','is_account'=>1])->value('id');
            if ($only) {
                $outerstr = explode('_', $arr['outerstr']);
                //领卡
                if ($arr['type'] == 'getcard') {
                    $CardShareUser = new CardShareUser();
                    $CardShareUser->where(['card_id' => $arr['card_id'], 'outerstr' => $arr['outerstr']])->setInc('get_ren');
                    //分享记录
                    $CardShareLog = new CardShareLog();
                    $dataget['get_openid'] = $arr['get_openid'];
                    $dataget['openid'] = reset($outerstr);
                    $dataget['get_code'] = $arr['get_code'];
                    $dataget['card_id'] = $arr['card_id'];
                    $dataget['share_uid'] = $CardShareUser->where(['card_id' => $arr['card_id'], 'openid' => reset($outerstr)])->value('id');
                    $dataget['rule_id'] = $only;
                    $dataget['mid'] = $arr['mid'];
                    $dataget['top_mid'] = $arr['top_mid'];
                    $CardShareLog->allowField(true)->save($dataget);
                }
                //激活卡
                if ($arr['type'] == 'firecard') {
                    $CardShareUser = new CardShareUser();
                    $CardShareUser->where(['card_id' => $arr['card_id'], 'outerstr' => $arr['outerstr']])->setInc('fire_ren');
                    $ruleuser = $CardShareUser->where(['card_id' => $arr['card_id'], 'outerstr' => $arr['outerstr']])->find();
                    $arrs['rule_id'] = $only;
                    $arrs['openid'] = $ruleuser['openid'];
                    $arrs['card_id'] = $arr['card_id'];
                    $arrs['code'] = $ruleuser['code'];
                    //奖励积分
                    $bonus = $this->getsharebonus($arrs);
                    //奖励余额
                    $balance = $this->getsharebalance($arrs);



//                    $CardUserUpdate = new CardUserUpdate();
//                    //更新记录
//                    if (isset($bonus)) {
//                        $data['add_bonus'] = $bonus['bonus'];
//                    }
//                    if (isset($balance)) {
//                        $data['add_balance'] = $balance['add_balance'];
//                    }
//                    //更新记录
//                    $data['mid'] = $this->getmid($arr['card_id']);
//                    $data['openid'] = $ruleuser['openid'];
//                    $data['record_balance'] = '分享奖励';
//                    $data['record_bonus'] = '分享奖励';
//                    $data['code'] = $ruleuser['code'];
//                    $data['card_id'] = $arrs['card_id'];
//                    $data['con_username'] = 'SHAREGIFT';
//                    $data['hx_fs'] = 24;
//                    $data['type'] = 5;
//                    $data['cate'] = 3;
//                    $data['reason'] = 6;
//                    $data['source'] = 7;
//                    $data['create_time'] = time();
//                    $CardUserUpdate->allowField(true)->save($data);
                    //分享记录
                    $CardShareLog = new CardShareLog();
                    if (isset($bonus)) {
                        $dataget['bonus'] = $bonus['bonus'];
                    }
                    if (isset($balance)) {
                        $dataget['balance'] = $balance['add_balance'];
                    }
                    if (isset($dataget['bonus']) || isset($dataget['balance'])) {
                        $CardShareLog->allowField(true)->save($dataget, ['get_code' => $arr['get_code'], 'get_openid' => $arr['get_openid']]);
                    }
                    //END    送券 START
                    $arrs['get_code'] = $arr['get_code'];
                    $cards = $this->getsharecards($arrs);
                }
            }
        } else {
            return 1;
        }
    }

    //积分记录
    /*
     * nickname  record_bonus  us_id  top_mid  mid  c_id  openid  card_id  code  reason  add_bonus  hx_fs  source  orderid
     *
     */
    private function rec_user_bonus($param){
        try{
            $option = $param;
            $option['bd_cate'] = 'bonus';
            $option['source'] = 'online';
//            $option['card_id'] = $param['card_id'];
//            $option['code'] = $param['code'];
//            $option['orderid'] = '';
//            $option['num'] =  $param['add_bonus'];
//            $option['type'] = $param['type'];//变动 1增加 2减少
//            $option['cate'] = $param['cate'];  //变动类型
//            $option['pay_cate'] = $param['pay_cate']; //支付方式
//            $option['source'] = $param['source'];  //来源
//            $option['remark'] = $param['record_bonus']; //备注
//            $option['action_user'] = $param['con_username'];//操作人

            $Fztest = new WnCardObj($option);

            $Fztest->init();
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            trace("rec_user_bonus:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","card_bonus","e:",$res);
        }
    }

    //余额记录
    /*
     * nickname  record_bonus  us_id  top_mid  mid  c_id  openid  card_id  code  reason  add_bonus  hx_fs  source  orderid
     *
     */
    private function rec_user_fee($param){
        try{
            $option = $param;
            $option['bd_cate'] = 'balance';
            $option['source'] = 'online';
//            $option['card_id'] = $param['card_id'];
//            $option['code'] = $param['code'];
//            $option['orderid'] = '';
//            $option['num'] =  $param['add_bonus'];
//            $option['type'] = $param['type'];//变动 1增加 2减少
//            $option['cate'] = $param['cate'];  //变动类型
//            $option['pay_cate'] = $param['pay_cate']; //支付方式
//            $option['source'] = $param['source'];  //来源
//            $option['remark'] = $param['record_bonus']; //备注
//            $option['action_user'] = $param['con_username'];//操作人
            $Fztest = new WnCardObj($option);
            $Fztest->init();
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","rec_user_fee","e:",$res);
            trace("rec_user_fee:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //分享领取奖励积分
    public function getsharebonus($arrs)
    {
        try{
            $CardShareRule = new CardShareRule();
            $ruleinfo = $CardShareRule->where(['id' => $arrs['rule_id']])->find();

            if ($ruleinfo['reward_bonus'] > 0 && $ruleinfo['is_bonus'] == "Y") {
                $data['card_id'] = $arrs['card_id'];
                $data['code'] = $arrs['code'];
                $data['num'] = $ruleinfo['reward_bonus'];
                $data['remark'] = '分享有礼';
                $data['type'] = 1;
                $data['cate'] = 7;
                $data['pay_cate'] = 24;
                $data['source'] = 7;
                $data['orderid'] = '';
//                $data['remark'] = $data['record_bonus']; //备注
                $data['action_user'] = 'SHAREGIFT';//操作人

                $this->rec_user_bonus($data);
                $bonus['bonus'] = $ruleinfo['reward_bonus'];
            }else{
                $bonus['bonus'] = 0;
            }
            return $bonus;
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","share_bonus","e:",$res);
            trace("getsharebonus:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }

    }

    //分享领取奖励余额
    public function getsharebalance($arrs)
    {
        try{
            $CardShareRule = new CardShareRule();
            $ruleinfo = $CardShareRule->where(['id' => $arrs['rule_id']])->find();
            if ($ruleinfo['reward_balance'] > 0 && $ruleinfo['is_balance'] == "Y") {
                $data['card_id'] = $arrs['card_id'];
                $data['code'] = $arrs['code'];
                $data['num'] = $ruleinfo['reward_balance'];
                $data['remark'] = '分享有礼';
                $data['type'] = 1;
                $data['cate'] = 7;
                $data['pay_cate'] = 24;
                $data['source'] = 7;
                $data['orderid'] = '';
                $data['is_bonus'] = 'no';
//                $data['remark'] = $data['record_bonus']; //备注
                $data['action_user'] = 'SHAREGIFT';//操作人
                $this->rec_user_fee($data);
                $balance['add_balance'] = $ruleinfo['reward_balance'];
            }else{
                $balance['add_balance'] = 0;
            }
            return $balance;
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","share_balance","e:",$res);
            trace("getsharebalance:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }


    //分享领取奖励余额
    public function getsharecards($arrs)
    {
        try{
           
            $CardShareRule = new CardShareRule();
            $ruleinfo = $CardShareRule->where(['id' => $arrs['rule_id']])->find();
            if ($ruleinfo['zs_no'] > 0 && $ruleinfo['is_cards'] == "Y") {
                $data['card_id'] = $arrs['card_id'];
                $data['openid'] = $arrs['openid'];
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where($data)->field('top_mid,mid,code,openid,nickname')->find();
                $data['get_code'] = $arrs['get_code'];
                $data['top_mid'] = $user['top_mid'];
                $data['code'] = $user['code'];
                $data['mid'] = $user['mid'];
                $data['nickname'] = $user['nickname'];
                $CardPuttest = new CardPut();
                $res['cards'] = $CardPuttest->putsharecards($data,$ruleinfo);
            }else{
                $res['cards'] = '';
            }
            return $res;
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","share_cards","e:",$res);
            trace("getsharecards:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //群发投放
    public function massputcard($arr)
    {
        $map['mid'] = $arr['mid'];
        $CardPutRule = new CardPutRule();
        $cardid = $CardPutRule->where($map)->value('card_id');
        $data = [
            "touser" => [
                $arr['openid']
            ],
            "wxcard" => [
                "card_id" => $cardid
            ],
            "msgtype" => "wxcard",
        ];
        //配置注入
        $mid = $map['mid'];
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $wxObj->mesgSend($data);
    }

    //客服消息投放
    public function mesgputcard($arr)
    {
        $map['mid'] = $arr['mid'];
        $CardPutRule = new CardPutRule();
        $cardid = $CardPutRule->where($map)->value('card_id');
        $data = [
            "touser" => $arr['openid'],
            "wxcard" => [
                "card_id" => $cardid
            ],
            "msgtype" => "wxcard",
        ];
        //配置注入
        $mid = $map['mid'];
        $options = $this->option($mid);
        $wxObj = new Wxobjopen($options);
        $wxObj->custMesg($data);
    }

    //判断激活状态并停止
    private function checkfire($arr)
    {
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($arr)->field('fire')->find();
        return $user;
        if ($user['fire'] == 1) {
            exit();
        }
    }

    //激活
    public function userfirecard($datas)
    {
        $map['card_id'] = $datas['cardid'];
        $map['code'] = $datas['usercardcode'];
        $resc = $this->checkfire($map);
        if ($resc['fire'] == 1 || $resc['fire'] == "1"){
            $this->upfireuserinfo($datas);
            exit();
        }
        //获取会员填写激活信息
        $arr = array(
            'card_id' => $datas['cardid'],
            'code' => $datas['usercardcode']
        );
        //获取会员填写信息
        $info = $this->getfireinfo($arr);
        if ($info['errcode'] == 0) {
            $this->init_bonus($arr);
            $CardUserGet = new CardUserGet();
            $udata = $this->fillgetinfo($info);
            //同步积分
            $CardMember = new CardMember();
            //该卡信息
            $card = $CardMember->where(['card_id'=>$datas['cardid']])->field('syn_is_exist,supply_bonus,card_id,mid')->find();
            if ((int)$card['supply_bonus'] == 1) {
                $udata['bonus'] = $this->getcardbonus($datas['cardid']);
                $datass['add_bonus'] = $udata['bonus'];
                $datass['card_id'] = $arr['card_id'];
                $datass['openid'] = $datas['openid'];
                $datass['code'] = $datas['usercardcode'];
                $datass['con_username'] = 'FIREGIFT';
                $datass['record_bonus'] = '激活赠送';
                $datass['hx_fs'] = 25;
                $datass['type'] = 3;
                $datass['cate'] = 1;
                $datass['reason'] = 4;
                $datass['source'] = 7;
                $datass['create_time'] = time();
                $datass['mid'] = $card['mid'];
//                $CardUserUpdate = new CardUserUpdate();
//                $CardUserUpdate->allowField(true)->save($datass);
                $CardUserBonus = new CardUserBonus();
                $mac['card_id'] = $datass['card_id'];
                $mac['code'] = $datass['code'];
                $mac['cate'] = 5;
                $mac['action_user'] = 'FIREGIFT';
                $is_us_bonus = $CardUserBonus->where($mac)->value('id');
                if (!$is_us_bonus) {
                    $this->firebonus($datass);
                }
            }
            //会员填写信息更新存入USERGET表
            if (isset($udata['fireinfo']) && isset($udata['fireinfo']['实体卡号'])) {
                $fireinfo = json_decode($udata['fireinfo'], true);
                $udata['old_code'] = $fireinfo['实体卡号'];
            }
            $udata['fire_time'] = time();
            $userdata = $udata;
            unset($userdata['bonus']);
            $CardUserGet->allowField(true)->save($userdata, ['card_id' => $map['card_id'], 'code' => $map['code']]);
            unset($udata['fire_time']);
            $this->firegivecards(['card_id' => $map['card_id'], 'code' => $map['code']]);
            //分享奖励
            $arrshare['card_id'] = $arr['card_id'];
            $arrshare['outerstr'] = $CardUserGet->where(['card_id' => $map['card_id'], 'code' => $map['code']])->value('outerstr');
            $arrshare['type'] = 'firecard';
            $arrshare['get_code'] = $datas['usercardcode'];
            $arrshare['get_openid'] = $datas['openid'];
            $share = $this->shareget($arrshare);
            //获取mid
            $mid = $card['mid'];
            //同步会员数据
            //判断同步
            if ($card['syn_is_exist'] == '1' || $card['syn_is_exist'] == '2') {
                if (!empty($udata['old_code'])) {
                    $CardLeaduser = new CardLeaduser();
                    //手机号为条件
                    if ($card['syn_is_exist'] == '1') {
                        $synuser = $CardLeaduser->where(['phone' => $udata['phone'], 'mid' => $mid])->find();
                        //是否已被同步
                        if ((int)$synuser['statu'] == '1') {
                            return 1;
                        }
                    } else {
                        //旧卡号为条件
                        $fireinfo = json_decode($udata['fireinfo'], true);
                        $udata['old_code'] = $fireinfo['实体卡号'];
                        $synuser = $CardLeaduser->where(['old_code' => $udata['old_code'], 'mid' => $mid])->find();
                        //是否已被同步
                        if ($synuser['statu'] == 1) {
                            exit();
                        }
                    }
                    if (isset($synuser) && $synuser['statu'] == 0) {
                        $sdata = [
                            'code' => $datas['usercardcode'],
                            'card_id' => $datas['cardid'],
                            'bonus' => $synuser['bonus'],
                            'balance' => $synuser['balance'],
                            'openid' => $datas['openid'],
                            'record_bonus' => '同步奖励',
                        ];
                        $synres = $this->synbonus($sdata);
                        $synresb = $this->synbalance($sdata);
                        //存入核销表
                        $cdata['card_id'] = $datas['cardid'];
                        $cdata['code'] = $datas['usercardcode'];
                        $cdata['add_bonus'] = $synuser['bonus'];
                        $cdata['add_balance'] = $synuser['balance'];
                        $cdata['openid'] = $datas['openid'];
                        $cdata['mid'] = $mid;
                        $cdata['con_username'] = 'SYNCGIFT';
                        $cdata['record_balance'] = '同步';
                        $cdata['record_bonus'] = $sdata['record_bonus'];
                        $cdata['hx_fs'] = 23;
                        $cdata['create_time'] = time();
                        $CardUserUpdate = new CardUserUpdate();
                        $CardUserUpdate->allowField(true)->save($cdata);
                        $ldata['statu'] = 1;
                        $ldata['update_time'] = time();
                        $ldata['new_code'] = $datas['usercardcode'];
                        $wherel['id'] = $synuser['id'];
                        $CardLeaduser->allowField(true)->save($ldata, $wherel);
                        return 1;
                    } else {
                        return 3;
                    }
                }else{
                    return 6;
                }
            } else {
                return 4;
            }
        } else {
            return 5;
        }
    }

    //更新激活数据
    private function upfireuserinfo($param){
        try{
            //获取会员填写激活信息
            $arr = array(
                'card_id' => $param['cardid'],
                'code' => $param['usercardcode']
            );
            //获取会员填写信息
            $info = $this->getfireinfo($arr);
            if ($info['errcode'] == 0) {
                $user = $this->fillgetinfo($info);
                $CardUserGet = new CardUserGet();
                $CardUserGet->allowField(true)->save($user, $arr);
            }
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos", "wxcard", "getedituserinfo", "e:", $res);
            trace("upfireuserinfo:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //激活赠送积分
    private function firebonus($param){
        try{
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['add_bonus'];
            $data['type'] = 1;
            $data['cate'] = 5;
            $data['pay_cate'] = 25;
            $data['source'] = 'online';
            $data['orderid'] = '';
            $data['remark'] = $param['record_bonus']; //备注
            $data['action_user'] = $param['con_username'];//操作人
            $data['is_write'] = 'no';
            $this->rec_user_bonus($data);
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","fire_bonus","e:",$res);
            trace("firebonus:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //同步送积分
    public function synbonus($param){
        try{
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['bonus'];
            $data['type'] = 1;
            $data['cate'] = 8;
            $data['pay_cate'] = 23;
            $data['source'] = 'online';
            $data['orderid'] = '';
            $data['remark'] = '同步奖励'; //备注
            $data['action_user'] = 'SYNCGIFT';//操作人
            $this->rec_user_bonus($data);
            $res['errcode'] = 1;
            return $res;
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","syn_bonus","e:",$res);
            trace("synbonus:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //同步送余额
    public function synbalance($param){
        try{
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['balance'];
            $data['type'] = 1;
            $data['cate'] = 8;
            $data['pay_cate'] = 23;
            $data['source'] = 'online';
            $data['orderid'] = '';
            $data['remark'] = '同步奖励'; //备注
            $data['action_user'] = 'SYNCGIFT';//操作人
            $data['is_bonus'] = 'no';//操作人
            $this->rec_user_fee($data);
            $res['errcode'] = 1;
            return $res;
        } catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","syn_balance","e:",$res);
            trace("synbalance:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //初始化积分余额
    public function init_bonus($arr)
    {
        //实例化微信
        try {
            $option = $this->option($arr['card_id']);
            $WxObj = new Wxobjopen($option);
            $data = [
                'code' => $arr['code'],
                'card_id' => $arr['card_id'],
                'record_bonus' => 0,       //说明
                'custom_field_value2' => 0.00 . '元',
                'notify_optional' => [
                    'is_notify_bonus' => false,
                    'is_notify_balance' => false,
                    'is_notify_custom_field2' => false,
                ],
            ];
            $res = $WxObj->updateUserInfo($data);
        } catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
        }
        return $res;
    }

    //查询激活信息
    public function getfireinfo($data)
    {
        $options = $this->option($data['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->userGetInfo($data);
        return $res;
    }

    //写入领取用户信息处理
    public function recgetuserinfo($data){
        try {
            $options = $this->option($data['card_id']);
            $wxObj = new Wxobjopen($options);
            $info = $wxObj->userGetInfo($data);
            //接口END
            $arr['nickname'] = $info['nickname'];
            $arr['sex'] = $info['sex'] == 'MALE' ? 1 : 0;
            $CardUserGet = new CardUserGet();
            $map['openid'] = $info['openid'];
            $res = $CardUserGet->allowField(true)->save($arr,$data);
        } catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
        }
    }

    //更新会员归属门店
    public function rec_gsmid($param){
        try {
            $map['code'] = $param['code'];
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where($map)->field('id,code,outerstr,sourec,card_id')->find();
            if ($user) {
                //为空时或支付后送券则更新归属为创建门店
                if ($user['outerstr'] == '' || $user['outerstr'] == null || $user['sourec'] == "SOURCE_SCENE_TPMSG_SEND_MEMBER_AFTER_PAY") {
                    $CardMember = new CardMember();
                    $sql['card_id'] = $user['card_id'];
                    $card = $CardMember->where($sql)->field('mid')->find();
                    //END
                    $data['gs_mid'] = $card['mid'];
                    $CardUserGet->save($data, $map);
                    $result = 'success';
                } else {
                    //不为空时
                    //是否有规则
                    if (strpos($user['outerstr'], '_')) {
                        $CardShareUser = new CardShareUser();
                        $top_user_s = $CardShareUser->where(['card_id' => $user['card_id'], 'outerstr' => $user['outerstr']])->field('code,openid')->find();
                        //查找分享用户
                        if ($top_user_s) {
                            $top_user = $CardUserGet->where(['code' => $top_user_s['code']])->field('id,code,outerstr,sourec,card_id,gs_mid')->find();
                            //分享用户是否领卡
                            if ($top_user) {
                                //分享用户是否又归属门店
                                if ($top_user['gs_mid']) {
                                    $data['gs_mid'] = $top_user['gs_mid'];
                                    $CardUserGet->save($data, $map);
                                    $result = 'success';
                                } else {
                                    $result = 'error';
                                }
                            } else {
                                $result = 'error';
                            }
                        } else {
                            $result = 'error';
                        }
                    } else {
                        //小于五位时更新归属为场景值
                        if (strlen($user['outerstr']) < 5 && is_numeric($user['outerstr'])) {
                            $data['gs_mid'] = $user['outerstr'];
                            $CardUserGet->save($data, $map);
                            $result = 'success';
                        } else {
                            $result = 'error';
                        }
                    }
                }
                //是否更新归属门店成功
                if ($result == 'error') {
                    $CardMember = new CardMember();
                    $sql['card_id'] = $user['card_id'];
                    $card = $CardMember->where($sql)->field('mid')->find();
                    //END
                    $data['gs_mid'] = $card['mid'];
                    $CardUserGet->save($data, $map);
                    $result = 'success';
                }
            }
        }catch (\Exception $e) {
//            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","wxcard","gs_mid","e:",$res);
            trace("rec_gsmid:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //激活填写数据的处理
    public function fillgetinfo($info)
    {
        $param = $info['user_info']['common_field_list'];
        foreach ($param as $k => $v) {
            switch ($v['name']) {
                case "USER_FORM_INFO_FLAG_MOBILE":
                    $arr['phone'] = $v['value'];
                    break;
                case "USER_FORM_INFO_FLAG_LOCATION":
                    if (isset($v['value'])) {
                        $arr['address'] = $v['value'];
                    } else {
                        $arr['address'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_BIRTHDAY":
                    if (isset($v['value'])) {
                        $arr['birthday'] = $v['value'];
                        $arr['feteday'] = date("m-d", strtotime($v['value']));
                    } else {
                        $arr['birthday'] = '';
                        $arr['feteday'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_NAME":
                    if (isset($v['value'])) {
                        $arr['name'] = $v['value'];
                    } else {
                        $arr['name'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_IDCARD":
                    if (isset($v['value'])) {
                        $arr['idnumber'] = $v['value'];
                    } else {
                        $arr['idnumber'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EMAIL":
                    if (isset($v['value'])) {
                        $arr['email'] = $v['value'];
                    } else {
                        $arr['email'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EDUCATION_BACKGRO":
                    if (isset($v['value'])) {
                        $arr['backgro'] = $v['value'];
                    } else {
                        $arr['backgro'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INDUSTRY":
                    if (isset($v['value'])) {
                        $arr['industry'] = $v['value'];
                    } else {
                        $arr['industry'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INCOME":
                    if (isset($v['value'])) {
                        $arr['income'] = $v['value'];
                    } else {
                        $arr['income'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_HABIT":
                    if (isset($v['value'])) {
                        $arr['habit'] = $v['value'];
                    } else {
                        $arr['habit'] = '';
                    }
                    break;
            }
        }
        $arr['old_code'] = '';
        if (isset($info['user_info']['custom_field_list'])) {
            foreach ($info['user_info']['custom_field_list'] as $k => $v) {
                $userinfo[$v['name']] = $v['value'];
            }
            if (isset($userinfo)) {
                $arr['fireinfo'] = json_encode($userinfo, JSON_UNESCAPED_UNICODE);
                if (isset($userinfo['实体卡号'])) {
                    $arr['old_code'] = $userinfo['实体卡号'];
                }
            }
        }
        $arr['nickname'] = $info['nickname'];
        $arr['sex'] = $info['sex'] == 'MALE' ? 1 : 0;
        $arr['fire'] = 1;
        return $arr;
    }

    //获取会员卡初始信息
    public function getcardbonus($arr)
    {
        $CardMember = new CardMember();
        $card = $CardMember->where('card_id', $arr)->value('bonus_rule');
        $card = json_decode($card, true);
        $int_bonus = $card['init_increase_bonus'];
        return $int_bonus;
    }

    //同步传入积分
    public function synusers($arr)
    {
        $data['code'] = $arr['code'];
        $data['card_id'] = $arr['card_id'];
        $data['record_bonus'] = $arr['record_bonus'];
        $data['add_bonus'] = $arr['bonus'];
        $data['notify_optional']['is_notify_bonus'] = true;
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->updateUserInfo($data);
        return $res;
    }

    //同步传入积分
    public function synuser($arr)
    {
        $data['code'] = $arr['code'];
        $data['card_id'] = $arr['card_id'];
        $data['record_bonus'] = $arr['record_bonus'];
        $data['add_bonus'] = $arr['bonus'];
        $data['custom_field_value2'] = $arr['balance'].'元';
        $data['notify_optional']['is_notify_bonus'] = true;
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->updateUserInfo($data);
        return $res;
    }

    //同步奖励余额
    public function leaduserbalance($arrs)
    {
        if ($arrs['balance'] > 0) {
            $CardUserGet = new CardUserGet();
            $map['card_id'] = $arrs['card_id'];
            $map['code'] = $arrs['code'];
            $CardUserGet->where($map)->setInc('balance', $arrs['balance']);
            $data['card_id'] = $arrs['card_id'];
            $data['type'] = 5;
            $data['openid'] = $arrs['openid'];
            $data['add_balance'] = $arrs['balance'];
            $data['balance'] = $CardUserGet->where(['code' => $arrs['code'], 'card_id' => $arrs['card_id']])->value('balance');
            $data['tplmesg_info'] = $this->balancesendmesg($data);
            $data['errcode'] = 0;
        } else {
            $data['errcode'] = 9001;
        }
        return $data;
    }

    //删除
    public function userdelcard($datas)
    {
        $map['openid'] = $datas['openid'];
        $map['card_id'] = $datas['card_id'];
        $map['code'] = $datas['code'];
        $data['del_time'] = $datas['create_time'];
        $data['have'] = 0;
        $CardUserGet = new CardUserGet();
        $res = $CardUserGet->where($map)->update($data);
        $CreateNotify = new CreateNotify();
        $CreateNotify->cards_del_notify($datas);
    }


    //核销
    public function userconsumecard($datas)
    {
        //修改卡券状态
        $map['openid'] = !empty($datas['FromUserName'])?$datas['FromUserName']:"";             //openid
        $map['card_id'] = $datas['CardId'];            //card_id
        $map['code'] = $datas['UserCardCode'];         //code
        $data['consume_time'] = time();
        $data['statu'] = 2;
        $CardUserGet = new CardUserGet();
        $CardUserGet->allowField(true)->save($data, $map);
        //END
    }

    //更新优惠券数量
    // change_type  openid  code
    public function update_cardus_cardsnum($param){
        try {
            $CardUserGet = new CardUserGet();
            if ($param['change_type'] == 'consum'){
                $map['openid'] = $param['openid'];
                $map['code'] = $param['code'];
                $usercards = $CardUserGet->where($map)->field('top_mid,openid')->find();
                if ($usercards){
                    $usercards['card_type'] = 'MEMBER_CARD';
                    $usercards['fire'] = 1;
                    $usercards['have'] = 1;
                    $user = $CardUserGet->where($usercards)->field('openid,card_id,code')->find();
                    if ($user){
                        $user['cell_type'] = 'three_cell';
                        $CardCustom = new CardCustom();
                        $CardCustom->carry_custom($user);
                    }
                }
            }else{
                $usercards['openid'] = $param['openid'];
                $usercards['top_mid'] = $param['top_mid'];
                $usercards['card_type'] = 'MEMBER_CARD';
                $usercards['fire'] = 1;
                $usercards['have'] = 1;
                $user = $CardUserGet->where($usercards)->field('openid,card_id,code')->find();
                if ($user){
                    $user['cell_type'] = 'three_cell';
                    $CardCustom = new CardCustom();
                    $CardCustom->carry_custom($user);
                }
            }
        } catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
        }
    }

    //更新
    public function userupdatecard($datas)
    {
        $data['mid'] = 1;
        $data['openid'] = $datas['openid'];
        $data['card_id'] = $datas['cardid'];
        $data['code'] = $datas['code'];
        $data['add_bonus'] = $datas['modifybonus'];
        $data['add_balance'] = $datas['modifybalance'];
        $data['creattime'] = time();
        $data['type'] = 1;
        $data['source'] = json_encode($datas);
        $CardUserUpdate = new CardUserUpdate();
        $CardUserUpdate->save($data);
    }

    //库存报警
    public function userskucard($datas)
    {
        $map['card_id'] = $datas['cardid'];
        $CardMerber = new CardMember();
        $CardGeneral = new CardGeneral();
        $only = $CardMerber->where($map)->value('id');
        if (empty($only)) {
            $CardGeneral->where($map)->setField('datail', $datas['detail']);
        } else {
            $CardMerber->where($map)->setField('datail', $datas['detail']);
        }
    }


    //投放
    public function put($card_id)
    {
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->option($card_id);
        $wxObj = new Wxobjopen($options);
        $noncestr = $wxObj->generateNonceStr();
        $res['config'] = $wxObj->getJsSign($url, '', $noncestr);
        $res['config']['debug'] = true;
        $res['config']['jsApiList'] = array('addCard', 'openCard', 'chooseCard');
        $res['addcard'] = $wxObj->wxAddCard($card_id, $noncestr);
        return $res;
    }

    //JSSDK投放
    public function jssdk($type, $arr = '')
    {
        $options = $this->option($arr);
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $wxObj = new Wxobjopen($options);
        if ($type == 0) {
            $res = $wxObj->getJsSign($url);
            return $res;
        }
        if ($type == 1) {
            $res = $wxObj->getJsSign($url);
            return $res;
        }
    }


    //接收客户端信息
    public function getCashier($arr)
    {
        $map['mid'] = $arr['mid'];  //商户ID
        $map['openid'] = $arr['openid'];    //openid
        $CardMember = new CardMember();
        $CardUserGet = new CardUserGet();
        $cardid = $CardMember->where($map)->value('card_id');    //card_id
        //更新数据
        $data = [
            'bonus' => $arr['bonus'],
            'balance' => $arr['balance'],
        ];
        $res = $CardUserGet->where('card_id=' . $cardid)->update($data);
        //判断输出
        if ($res == false) {
            echo "成功";
        } else {
            echo "失败";
        }
    }

    //关注
    public function getfansinfo($datas)
    {
        $openid = $datas['openid'];
        $CardFans = new CardFans();
        $map['openid'] = $openid;
        $map['gh_id'] = $datas['gh_id'];
        $isone = $CardFans->where($map)->value('id');
        //老用户重新关注
        if (isset($isone)) {
            $option = $this->options($datas['gh_id']);
            $WxObj = new Wxobjopen($option);
            $user = $WxObj->getUserInfo($openid);
            $data['nickname'] = $user['nickname'];
            $data['head_url'] = $user['headimgurl'];
            $data['info'] = json_encode($user, JSON_UNESCAPED_UNICODE);
            $data['statu'] = 1;
            $data['update_time'] = time();
            $CardFans->allowField(true)->save($data, $map);
            //从未关注新用户
        } else {
            $option = $this->options($datas['gh_id']);
            $WxObj = new Wxobjopen($option);
            $users = $WxObj->getUserInfo($openid);
            $WxOpen = new WxOpen();
            $wx_open_id = $WxOpen->where('gh_id', $datas['gh_id'])->value('id');
            $data['wx_open_id'] = $wx_open_id;
            $data['gh_id'] = $datas['gh_id'];
            $data['statu'] = $users['subscribe'];
            $data['openid'] = $users['openid'];
            $data['nickname'] = $users['nickname'];
            $data['sex'] = $users['sex'];
            $data['city'] = $users['city'];
            $data['head_url'] = $users['headimgurl'];
            $data['province'] = $users['province'];
            $data['groupid'] = $users['groupid'];
            $data['create_time'] = time();
            $CardFans->allowField(true)->validate(['openid'  => 'require|unique:CardFans'])->save($data);
        }
    }

    //取关
    public function offfansinfo($datas)
    {
        $CardFans = new CardFans();
        $map['gh_id'] = $datas['gh_id'];
        $map['openid'] = $datas['openid'];
        $data['statu'] = 2;
        $data['update_time'] = time();
        $res = $CardFans->allowField(true)->save($data, $map);
    }

    //模版消息yue
    public function balancesendmesg($arr)
    {
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $map['id'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
        $wx_open_id = $Merchant->where($map)->value('wx_open_id');
        //初始化微信类
        $options = $this->option($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_ye_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            case "3":
                $type = "奖励";
                break;
            case "5":
                $type = "同步";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = floor($arr['add_balance'] * 100) / 100;
        $balance = floor($arr['balance'] * 100) / 100;
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance . '元', 'color' => '#000'],
                'keyword4' => ['value' => $balance . '元', 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        return $res;
    }



    //微信API参数
    public function options($gh_id)
    {
        Session::set('openid', null);
        $Momerchant = new Momerchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mab['gh_id'] = $gh_id;
        $users = $WxOpen->where($mab)->find();
        $agent = $Momerchant->where(['wx_open_id'=>$users['id']])->value('agent');
        $config = $Agent->where(array('id' => $agent))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数
    public function option($card_id)
    {
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->field('authorizer_appid,authorizer_refresh_token')->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


}